package com.gethb.prod.service.impl;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.gethb.data.dao.MessageMapper;
import com.gethb.data.mdo.MessageDo;
import com.gethb.prod.service.IAgainMessageService;
import com.gethb.prod.vo.AgainMessageInVo;
import com.gethb.prod.vo.AgainMessageOutVo;
import com.gethb.pub.utils.BaseInVo;
import com.gethb.pub.utils.ShortMessageUtils;


@Component("againMessageService")
public class AgainMessageServiceImpl implements IAgainMessageService {

    private static final Logger LOG = LoggerFactory.getLogger(AgainMessageServiceImpl.class);

    @Resource
    MessageMapper messageMapper;//接口

    @Override
    public String sendAgainMessage(String jsonString) {
        LOG.info("重新发送短信start！");
        AgainMessageOutVo outVo = new AgainMessageOutVo();
        AgainMessageInVo inVo = BaseInVo.parseJsonStr(jsonString, AgainMessageInVo.class);
        LOG.info("重发短信手机号：" + inVo.getMblphNo());
        LOG.info("重发短信次数：" + inVo.getNumber());
        LOG.info("重发短信ID：" + inVo.getMessageId());

        // 查询记录
        MessageDo messageDo = new MessageDo();
        messageDo.setMblphNo(inVo.getMblphNo());
        messageDo.setNumber(inVo.getNumber());
        messageDo.setMessageId(inVo.getMessageId());
        messageDo = messageMapper.findMessageDo(messageDo);
        LOG.info(messageDo.getRequestId());
        Integer number = Integer.valueOf(messageDo.getNumber()) + 1;
        if (11 > number) {
            messageDo.setNumber(String.valueOf((number)));
        } else {
            outVo.setNumber(messageDo.getNumber());
            outVo.setMessageId(messageDo.getMessageId());
            outVo.setState("Fail");
            return JSON.toJSONString(outVo);
        }
        messageDo.setCode(String.valueOf((int) ((Math.random() * 9 + 1) * 100000)));
        messageMapper.addNewMessage(messageDo);

        // 调用发送短信方法
        SendSmsResponse sendSmsResponse =
                ShortMessageUtils.requestMessage(messageDo);

        // 更新发送短信数据库结果
        messageDo.setBizId(sendSmsResponse.getBizId());
        messageDo.setErrCode(sendSmsResponse.getCode());
        messageDo.setRequestId(sendSmsResponse.getRequestId());
        messageDo.setErrInf(sendSmsResponse.getMessage());
        messageMapper.updateMessageResult(messageDo);

        // 返回数据
        outVo.setNumber(messageDo.getNumber());
        outVo.setState(sendSmsResponse.getCode());
        outVo.setMessageId(messageDo.getMessageId());

        LOG.info("重新发送短信end");
        return JSON.toJSONString(outVo);
    }

}
